package com.jason.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jason.base.BaseProcess;
import com.jason.core.config.jwt.JwtUtil;
import com.jason.core.util.SecurityUtil;
import com.jason.entity.SysUser;
import com.jason.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.security.sasl.AuthenticationException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class LoginController extends BaseProcess {

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    JwtUtil jwtUtil;

    /**
     * 用户登录
     *
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
    @ApiOperation(value = "登陆接口", notes = "登陆",  produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/login")
    public Object login(@RequestBody Map<String, Object> params){
        String username = String.valueOf(params.get("username"));
        String password = String.valueOf(params.get("password"));
        EntityWrapper<SysUser> entityWrapper = new EntityWrapper<>();
        Map<String, Object> map = new HashMap<>();
        SysUser queryEntity = new SysUser();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return setLoginFailResult();
        }
        queryEntity.setUsername(username);
        queryEntity.setPassword(SecurityUtil.encryptPassword(password));
        entityWrapper.setEntity(queryEntity);
        SysUser sysUser = sysUserService.selectOne(entityWrapper);
        if (sysUser != null){
            String token = jwtUtil.generateToken(sysUserService.selectUserRole(username));
            map.put("token", token);
            return setSuccessResult(map);
        }
        return setLoginFailResult();
    }

    /**
     * 用户注册
     *
     * @param sysUser  用户信息
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
    @PostMapping(value = "/register")
    public Object register(@RequestBody  SysUser sysUser) throws AuthenticationException {
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        return sysUserService.insertWithUser(sysUser);
    }

    /**
     * 刷新密钥
     *
     * @param authorization 原密钥
     * @return 新密钥
     * @throws AuthenticationException 错误信息
     */
    @GetMapping(value = "/refreshToken")
    public Object refreshToken(@RequestHeader String authorization) throws AuthenticationException {
        return jwtUtil.refreshToken(authorization);
    }


}